package whx.handler.adapter.impl;

import org.springframework.stereotype.Component;
import whx.annotation.RequestMapping;
import whx.annotation.RequestParam;
import whx.handler.adapter.HandlerAdapter;
import whx.springmvc.RequestMappingInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

@Component
public class AnnotationHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean support(Object handler) {
        return handler instanceof RequestMappingInfo;
    }

    @Override
    public Object handler(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //请求携带的参数
        Map<String,String[]> map = req.getParameterMap();
        RequestMappingInfo mappingInfo = ((RequestMappingInfo)handler);
        Method method = mappingInfo.getMethod();
        Parameter[] parameter = method.getParameters();
        Object[] paramValue = new Object[parameter.length];
        for(int i = 0;i<parameter.length;i++){
            for(Map.Entry<String,String[]> entry: map.entrySet()){
                if(entry.getKey().equals(parameter[i].getAnnotation(RequestParam.class).value())){
                    paramValue[i] = entry.getValue()[0];
                }
            }
        }
        return method.invoke(mappingInfo.getObject(),paramValue);
    }
}
